package com.fjec.common.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fjec.common.util.DateUtil;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

    private final static String longPattern = "yyyy-MM-dd HH:mm:ss";

    @Override
    public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        if (jp.getCurrentToken() == JsonToken.VALUE_STRING) {
            String value = jp.getText();
            if (StringUtils.hasText(value)) {
                try {
                    return autoMatch(value);
                } catch (Exception e) {
                    throw new IllegalArgumentException("this argument's format must yyyy-MM-dd HH:mm:ss");
                }
            }
            return null;

        }
        throw new JsonMappingException(jp, "Expected JSON String");
    }

    private LocalDateTime autoMatch(String strDate) {
        return DateUtil.parseLdt(strDate, longPattern);
    }

}
